import { defineConfig } from 'tsdown'
import { fileArr } from './build-utils'
import { cpSync, readFileSync, writeFileSync } from 'node:fs'
import { execSync } from 'node:child_process'
import {} from 'ant-design-vue'
let entryMap: Record<string, string> = {}
let exportMap: Record<
  string,
  // {
  //   types: string
  //   default: string
  // }
  string
> = {}

fileArr.forEach((file) => {
  let filteredFileName = file.replace('src/', '').replace('.ts', '').replace('.vue', '')
  entryMap[`./${filteredFileName}`] = file
  // exportMap[filteredFileName] = {
  //   types: './' + filteredFileName + '.d.ts',
  //   default: './' + filteredFileName + '.js',
  // }
  exportMap['./' + filteredFileName] = './' + filteredFileName + '.js'
})
export default defineConfig([
  {
    entry: entryMap,
    platform: 'browser',
    fromVite: true,
    dts: {
      vue: true,
    },
    unbundle: true,
    attw: false,
    onSuccess: () => {
      const packageJson = JSON.parse(readFileSync('./package.json', { encoding: 'utf-8' }))
      packageJson.exports = {
        './*': {
          types: './*.d.ts',
          default: './*.js',
        },
      }
      writeFileSync('./dist/package.json', JSON.stringify({ ...packageJson }, null, 2), {
        encoding: 'utf-8',
        flag: 'w',
      })
      let fileName = `./dist/${packageJson.name.replace('@', '').replace('/', '-')}-${
        packageJson.version
      }.tgz`
      console.log(`打包完成，文件路径为：${fileName}`)
      execSync('cd ./dist && pnpm pack')
      // 复制tgz文件到 example/example-vue3.15
      let tgzName = packageJson.name.replace('@', '').replace('/', '-') + '.tgz'
      const examplePath = `../example/vue3/${tgzName}`
      cpSync(fileName, examplePath)
      console.log(`tgz文件已复制到：${examplePath}`)
      execSync(`cd ../example/vue3 && npm install &&npm install ./${tgzName}`)
      console.log('案例项目依赖更新完毕')
    },
  },
])
